/* eslint-disable */
import React, { useState, Fragment, useEffect } from 'react';
import { connect } from 'dva';
import { Table, Card, Button, ConfigProvider } from 'antd';
import styles from './index.less';
import style from '../index.css';
import moment from 'moment';
import '../../global.css';
import Search from './search';
import AddPage from './addPage';
import TablePagination from '../../components/common/TablePagination';
import TreePagination from "../../components/common/TreePagination"
import { downloadExcel } from '../../services/home/homeService';
import { formatNoFixed, emptyText, reservedDecimalPlace } from '../../utils/commonUtil';
import AttachmentUploadModal from '../../components/common/AttachmentUploadModal';

import img from '../../assets/logo-loading.gif';

const Index = props => {
  const { dispatch, collectionModel, globalModel } = props;
  const { quotaList, lineTypeList, dataSource, total, currentPage, pageSize, loading, searchData, personalizedColumn, allData, treeColumns, attachmentUploadModalVisible,
    attachmentUploadModalList, attachmentUploadModalLoading, basicId, masterDataCode, ownerShipInstitution, ownerShipInstitutionCode, menuData } = collectionModel;
  const { userInfo } = globalModel
  const [showAdd, setShowAdd] = useState(false);
  const [detaileData, setDetaileData] = useState(null);
  const [isEdit, setIsEdit] = useState(null);
  const [receiptNumber, setReceiptNumber] = useState('');
  const [id, setId] = useState('');
  const [isDisabled, setIsDisabled] = useState(false);
  const [checkedKeys, setCheckedKeys] = useState([])
  const [list, setList] = useState([])

  const menuProcessing = (value) => {
    let count = menuData.filter(item => item.indexOf(value) !== -1)
    return count.length === 0
  }

  useEffect(() => {
    if (dataSource) {
      let data = dataSource.map(item => {
        item.details = menuProcessing("_details")
        return item
      })
      setList(JSON.parse(JSON.stringify(data)))
    }
  }, [menuData, dataSource])

  const createQutoProps = {
    onReset: () => {
      setReceiptNumber("");
      setId("");
      dispatch({ type: "collectionModel/updateState", payload: { currentPage: 1, pageSize: 10, searchData: null } });
      dispatch({ type: 'collectionModel/getListDatas', payload: { currentPage: 1, pageSize: 10 } });
    },
  };

  const addPageProps = {
    detaileData,
    lineTypeList,
    quotaList,
    receiptNumber,
    id,
    isEdit,
    isDisabled,
    deletes: menuProcessing("_delete"),
    add: menuProcessing("_add"),
    onCancel: () => {
      setShowAdd(false);
      dispatch({ type: "collectionModel/updateState", payload: { currentPage: 1, pageSize: 10, } });
      dispatch({ type: 'collectionModel/getListDatas', payload: { currentPage: 1, pageSize: 10, ...searchData } });
    },
    onRefresh: () => {
      dispatch({
        type: 'collectionModel/getListDatas', payload: {
          currentPage, pageSize, callback: (data) => {
            setDetaileData(data[selectIndex])
          }
        }
      });
    },
    onUpload: (record) => {
      dispatch({
        type: "collectionModel/updateState", payload: {
          attachmentUploadModalVisible: true, masterDataCode: record.masterDataEncoding, basicId: record.id,
          ownerShipInstitution: record.affiliatedInstitutionName, ownerShipInstitutionCode: record.affiliatedInstitution,
        }
      });
      dispatch({ type: 'collectionModel/selectAttachment', payload: { masterDataCode: record.masterDataEncoding, fileTypeCode: "payment_action", basicId: record.id, } });
    },
  };

  const columns = [
    {
      title: '操作', key: 'operate', width: 100, fixed: true,
      render: (text, record, index) => (
        <span>
          <Button type="link" size="small" onClick={() => goDetail(record, index)} disabled={record.details}>催款跟进</Button>
        </span>
      ),
    },
    { title: '归属机构', dataIndex: 'affiliatedInstitutionName', width: 150, key: 'affiliatedInstitutionName', ellipsis: true, },
    { title: '出库通知单号', dataIndex: 'outboundOrderNumber', width: 150, key: 'outboundOrderNumber', ellipsis: true, },
    { title: '销售订单号', dataIndex: 'sourcePrimaryKey', width: 200, key: 'sourcePrimaryKey', ellipsis: true, },
    { title: '交易方名称', dataIndex: 'counterpartyName', width: 200, key: 'counterpartyName', ellipsis: true, },
    { title: '主数据编码', dataIndex: 'masterDataEncoding', width: 150, key: 'masterDataEncoding', ellipsis: true, },
    { title: '邓白氏编码', dataIndex: 'dunsCode', width: 150, key: 'dunsCode', ellipsis: true, },
    { title: '催收等级', dataIndex: 'collectionLevelName', width: 100, key: 'collectionLevelName', },
    {
      title: '催收金额', dataIndex: 'actuallyTake', width: 150, key: 'actuallyTake',
      render: (text, record) => (<span>{text ? formatNoFixed(reservedDecimalPlace(text, 2)) : 0}</span>),
    },
    { title: '交易币种', dataIndex: 'currency', width: 100, key: 'currency', },
    { title: '付款条件', dataIndex: 'paymentTerm', width: 200, key: 'paymentTerm', ellipsis: true, },
    {
      title: '账期起算日', dataIndex: 'paymentDaysZeroDate', width: 120, key: 'paymentDaysZeroDate',
      render: (text, record) => (<span>{text ? moment(text).format('YYYY-MM-DD') : ""}</span>),
    },
    { title: '到期日', dataIndex: 'maturityDate', width: 120, key: 'maturityDate', },
    { title: '逾期天数', dataIndex: 'overDueDay', width: 100, key: 'overDueDay', },
    { title: '业务员', dataIndex: 'businessPeopleName', width: 100, key: 'businessPeopleName', },
    {
      title: '是否上传附件', dataIndex: 'isAttachment', width: 100, key: 'isAttachment',
      render: (text, record) => (
        <div>{record.attachmentList.length > 0 ? '是' : '否'}</div>
      )
    },
    {
      title: '是否反馈', dataIndex: 'isFeedback', width: 100, key: 'isFeedback',
      render: (text, record) => (
        <div>{record.reminderFollowUpList.length > 0 ? '是' : '否'}</div>
      )
    },
    {
      title: '最近反馈时间', dataIndex: 'feedbackTime', width: 200, key: 'feedbackTime',
      render: (text, record) => {
        if (record.reminderFollowUpList.length > 0) {
          return record.reminderFollowUpList[record.reminderFollowUpList.length - 1].feedbackTime
        }
      }
    },
    {
      title: '催款跟进', dataIndex: 'followUpDesc', width: 200, key: 'followUpDesc', ellipsis: true,
      render: (text, record) => {
        if (record.reminderFollowUpList.length > 0) {
          return record.reminderFollowUpList[record.reminderFollowUpList.length - 1].followUpDesc
        }
      }
    },
    {
      title: '是否已回款', dataIndex: 'isCancel', key: 'isCancel', width: 100,
    }
  ];

  const tablePaginationProps = {
    total,
    currentPage,
    pageSize,
    onPageChange: (page, size) => {
      console.log(searchData)
      dispatch({ type: 'collectionModel/updateState', payload: { loading: true, currentPage: page, pageSize: size }, });
      dispatch({ type: 'collectionModel/getListDatas', payload: { currentPage: page, pageSize: size, ...searchData } });
    },
    onShowSizeChange: (page, size) => {
      console.log(searchData)
      dispatch({ type: 'collectionModel/updateState', payload: { loading: true, currentPage: page, pageSize: size }, });
      dispatch({ type: 'collectionModel/getListDatas', payload: { currentPage: page, pageSize: size, ...searchData } });
    },
  };

  const goDetail = (record, index) => {
    setShowAdd(true);
    setDetaileData(record);
    setIsEdit(record.id)
    if (record.approvalStatus == 'new' || record.approvalStatus == 'denied') {
      setIsDisabled(false);
    } else {
      setIsDisabled(true);
    }
  }

  const onExport = () => {
    let headerNames = []
    let fieldNames = personalizedColumn
    let lineWidths = []
    fieldNames.forEach(item => {
      columns.forEach(i => {
        if (item === i.key) {
          headerNames.push(i.title)
          lineWidths.push(80)
        }
      })
    })
    downloadExcel({ headerNames, fieldNames, lineWidths, map: searchData ? JSON.stringify(searchData) : null, sign: 12 }, "催款行动").then(res => {

    });
  };

  const treePaginationProps = {
    personalizedColumn,
    allData,
    treeColumns,
    customKey: "collection",
    onPersonalizedColumn: (record) => {
      dispatch({ type: "collectionModel/updateState", payload: { personalizedColumn: record } });
    },
  }

  useEffect(() => {
    let list = ["operate",]
    let data = []
    columns.forEach(item => {
      if (list.indexOf(item.key) > -1) data.push(item)
    })
    personalizedColumn.forEach(item => {
      columns.forEach(i => {
        if (item == i.key) data.push(i)
      })
    })
    setCheckedKeys(data)
  }, [personalizedColumn])

  const attachmentUploadModalProps = {
    attachmentUploadModalVisible,
    attachmentUploadModalList,
    attachmentUploadModalLoading,
    masterDataCode,
    fileType: "催款行动",
    fileTypeCode: "payment_action",
    userInfo: JSON.parse(userInfo),
    ownerShipInstitution,
    ownerShipInstitutionCode,
    basicId,
    onCancel: () => {
      dispatch({ type: "collectionModel/updateState", payload: { attachmentUploadModalVisible: false } });
    },
    onDownload: (values) => {
      dispatch({ type: "collectionModel/downloadFile", payload: values });
    },
    onDelete: (values) => {
      dispatch({
        type: "collectionModel/deleteFileById", payload: {
          params: values, data: { masterDataCode, fileTypeCode: "payment_action", basicId, }
        }
      });
    },
    onUpload: (values) => {
      dispatch({ type: "collectionModel/updateState", payload: { attachmentUploadModalLoading: true } });
      dispatch({
        type: "collectionModel/uploadFile", payload: {
          params: values, data: { masterDataCode, fileTypeCode: "payment_action", basicId, }
        }
      });
    }
  };
  return (

    <div className={style.roomDiv}>
      <div style={{ display: showAdd ? 'none' : 'block' }}>
        <Fragment>
          <Search {...createQutoProps} />
          <Card>
            <div className={styles.toolbarText}>
              <div>催款行动列表</div>
              <div>
                <Button onClick={onExport} disabled={menuProcessing("_down")}>导出</Button>
                <TreePagination {...treePaginationProps} />
              </div>
            </div>
            <Table
              size="small"
              locale={{ emptyText }}
              columns={checkedKeys}
              dataSource={list}
              pagination={false}
              rowKey={record => record.id}
              loading={
                loading
                  ? {
                    indicator: (
                      <div>
                        <img src={img} alt="" />
                      </div>
                    ),
                  }
                  : false
              }
              scroll={{ x: 1000 }}
            />
            <TablePagination {...tablePaginationProps} />
          </Card>
        </Fragment>
      </div>
      {
        showAdd && <AddPage {...addPageProps} />
      }
      <AttachmentUploadModal {...attachmentUploadModalProps} />
    </div>


  );
};

function mapStateToProps({ collectionModel, globalModel }) {
  return { collectionModel, globalModel };
}

export default connect(mapStateToProps)(Index);
